package net.mmgg.android.bm;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

public class SearchDao {
	private int alreadyNum=0;//已经成功执行了的关键词个数
	private int successNum=0;
	private int errorNum=0;
	public synchronized void request(String action, Map<String, String> param, DataBean dataBean, int num, Handler handler) {
		int executeTime=0;
		long startTime=new Date().getTime();
		
		
		Log.i("===========", "关键词:" + dataBean.getKeyword().size() + "个");
		Log.i("===========", "URL:" + dataBean.getUrl().size() + "个");
		Log.i("===========", "最低执行个数:" + num + "个关键词");

		List<String> keywords = dataBean.getKeyword();
		List<String> urls = dataBean.getUrl();
		
		
		log(handler, "从服务器获取到关键词:" + keywords.size() + "个");
		log(handler, "从服务器获取到URL:" + urls.size() + "个");
		log(handler, "最低执行个数:" + num + "个关键词");
		
		log(handler, "程序开始执行...",true);
		
		for (int i = 0; i < keywords.size(); i++) {
			String key=keywords.get(i);
			boolean clickSuccess=false;
			if(alreadyNum>=num){
				break;
			}			
			//log(handler, "开始搜索关键字:" + key);
			log(handler,"搜索"+(i+1)+"开始");
			String keyword = "";
			try {
				keyword = URLEncoder.encode(key, "utf-8");
			} catch (UnsupportedEncodingException e1) {
				e1.printStackTrace();
				continue;
			}
			wait(500);

			String p=genParam(param,keyword);
			
			String url2 = "http://www.baidu.com" + action + "?" + p;
			
			String str2 = CustomerHttpClient.get(url2);
			if (null == str2) {
				//log(handler, "关键词:\" " + key + " \"搜索失败!");
				log(handler,"搜索失败");
				continue;
			}else{
				log(handler,"搜索成功,正在匹配...");
			}
			Document doc2 = Jsoup.parseBodyFragment(str2);
			// 推广链接
			Elements hrefT = doc2.getElementsByClass("ec_resitem");
			//log(handler, "获取到推广链接:" + hrefT.size() + "条");
			for (Element element : hrefT) {
				if (element.select("a.ec_title").first() == null) {
					//Log.i("ConfigUtil", "被忽略:" + element.text());
					continue;
				}
				String h = element.select("a.ec_title").first().attr("href");
				String u = element.select("span.ec_site").first().text();
				for (String url__ : urls) {
					if (u.indexOf(url__) != -1 || url__.indexOf(u) != -1) {
						log(handler, "匹配成功!");
						// hrefs.put(h, u);
						if(!clickSuccess){
							clickSuccess=clickHref(handler, u, h);
						}else{
							clickHref(handler, u, h);
						}
						break;
					}
				}
			}
			if(clickSuccess){
				alreadyNum++;
			}else{
				log(handler,"匹配失败,跳到下个关键词");
			}
		}
		executeTime=Long.valueOf((new Date().getTime()-startTime)/1000).intValue();
		log(handler, "执行成功:"+successNum+" 次",true);
		log(handler, "执行失败:"+errorNum+" 次",true);
		log(handler, "执行耗时:"+executeTime+" 秒",true);
		log(handler, "执行完毕!");
	}
	
	private String genParam(Map<String, String> param,String keyword){
		// 时间
		String time = String.valueOf(new Date().getTime());
		time = time.substring(time.length() - 7);
		String p = "";
		for (Map.Entry<String, String> e : param.entrySet()) {
			if (e.getKey().equals("ts")) {
				p += e.getKey() + "=" + time + "&";
			} else if (e.getKey().equals("word")) {
				p += e.getKey() + "=" + keyword + "&";
			} else {
				p += e.getKey() + "=" + e.getValue() + "&";
			}
		}
		p = p.substring(0, p.length() - 1);
		return p;
	}

	private boolean clickHref(Handler handler, String hrefname, String href) {
		boolean stop = false;
		boolean result=false;
		int maxExe = 0;
		wait(1000);
		while (!stop) {
			// log(handler, "模拟点击:" + hrefname);
			String s = CustomerHttpClient.get(href);
			if (null != s) {
				// log(handler, "点击:" + hrefname + "成功!!!");
				log(handler, "执行成功!");
				successNum++;
				result=true;
				break;
			} else {
				// log(handler, "点击:" + hrefname + "失败!!!", true);
				
				maxExe++;
				if (maxExe >= 3) {
					stop = true;
					log(handler, "执行失败!");
				}else{
					errorNum++;
					log(handler, "执行失败,3秒后重试!");
					wait(3000);
				}
			}
			
		}
		return result;
	}

	private void log(Handler handler, String message, boolean... isError) {
		
		Message msg = new Message();
		if (isError.length > 0 && isError[0]) {
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
			String m=sdf.format(new Date());
			msg.what = 1;
			msg.obj = m + ","+NetWorkUtil.ipAddress +">>>"+ message + "\n\n";
		} else {
			msg.what = 0;
			msg.obj = Thread.currentThread().getName() + ">>>" + message + "\n\n";
		}
		
		handler.sendMessage(msg);

	}

	/**
	 * 线程暂停多少秒
	 * 
	 * @param sec
	 */
	private void wait(int sec) {
		try {
			Thread.sleep(sec);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}
